package com.dtborad.myblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dtborad.myblog.common.CommonErrorCode;
import com.dtborad.myblog.common.Result;
import com.dtborad.myblog.entity.Likes;
import com.dtborad.myblog.entity.Points;
import com.dtborad.myblog.entity.Posts;
import com.dtborad.myblog.service.PointService;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/point")
@Slf4j
@Api(tags = "积分模块")
public class PointController {

    private static final long THROTTLE_DURATION_MS = TimeUnit.SECONDS.toMillis(5); // 设置节流时间为5秒
    private final ConcurrentHashMap<Long, Long> requestTimestamps = new ConcurrentHashMap<>();

    @Autowired
    private PointService pointService;

    @GetMapping("/{id}")
    public Result<Points> getDetail(@PathVariable Long id) {
        LambdaQueryWrapper<Points> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Points::getUserId, id);
        return Result.ofSuccess(pointService.getOne(wrapper));
    }

    @PutMapping("/update")
    public Result<Points> queryPoints(@RequestBody Points points){
        long currentTimestamp = System.currentTimeMillis();
        long userId = points.getUserId();
        // 检查并更新请求时间戳
        Long lastRequestTimestamp = requestTimestamps.put(userId, currentTimestamp);
        if (lastRequestTimestamp != null && (currentTimestamp - lastRequestTimestamp) < THROTTLE_DURATION_MS) {
            return Result.ofFail("1003", "请求过于频繁，请稍后再试");
        }
        try{
            LambdaQueryWrapper<Points> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Points::getUserId,points.getUserId());
            Points one = pointService.getOne(wrapper);
            Integer originPoints = one.getPoints();
            if(originPoints < points.getPoints()){
                return Result.ofFail("1002", "积分不足");
            }else{
                one.setPoints(originPoints - points.getPoints());
                //TODO 时区相差8小时
                one.setUpdateTime(new Date());
                pointService.updateById(one);
                return Result.ofSuccess(one);
            }
        }catch (Exception e){
            return Result.ofFail(CommonErrorCode.FAILURE);
        }
    }
}
